package com.dreamchaser.book.dao.impl;

import com.dreamchaser.book.dao.UserDao;
import com.dreamchaser.book.entity.User;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;

/**
 * User的数据库层
 * @author Dreamchaser
 */
public class UserDaoImpl implements UserDao {
    /**
     * 查询所有用户信息
     * @param conn connection连接对象
     * @return 所有用户信息的集合
     */
    public  List<User> selectUserAll(Connection conn){
        String sql="select * from user";
        List<User> list=new LinkedList<>();
        PreparedStatement statement=null;
        ResultSet resultSet =null;
        try {
            statement=conn.prepareStatement(sql);
            resultSet = statement.executeQuery();
            //解析resultSet，将对应的属性设置到user对象里
            while (resultSet.next()){
                User user=new User();
                user.setId(resultSet.getInt("id"));
                user.setAccount(resultSet.getString("account"));
                user.setPwd(resultSet.getString("pwd"));
                user.setRole(resultSet.getInt("role"));
                user.setUname(resultSet.getString("uname"));
                list.add(user);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return list;
    }

    /**
     * 根据条件（User）去查询相应的数据（取第一条数据）,如果没有符合条件的数据那么返回值为null
     * @param user 查询参数
     * @return 符合查询参数的User对象
     */
    public  User selectUserByCondition(Connection conn,User user){
        String sql="select * from user where "+user.getQueryCondition();
        Statement statement=null;
        ResultSet rs=null;
        User result=new User();
        try {
            statement=conn.createStatement();
            rs=statement.executeQuery(sql);
            if (rs.next()){
                result.setId(rs.getInt("id"));
                result.setAccount(rs.getString("account"));
                result.setPwd(rs.getString("pwd"));
                result.setRole(rs.getInt("role"));
                result.setUname(rs.getString("uname"));
            }else {
                return null;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return result;
    }
}
